package com.ocm.burnningstar.View;

import android.app.Fragment;
import android.content.Context;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.blankj.utilcode.util.ScreenUtils;
import com.ocm.burnningstar.Adapter.ClassXAdapter;
import com.ocm.burnningstar.Interface;
import com.ocm.burnningstar.MainActivity;
import com.ocm.burnningstar.Model.SportUser;
import com.ocm.burnningstar.R;
import com.ocm.burnningstar.Utils.Helper;
import com.shape.sdk.Course;
import com.shape.sdk.FitnessData;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.ocm.burnningstar.GlobalApplication.typeFaceClass;
import static com.ocm.burnningstar.GlobalApplication.typeFaceNum_Ob;

@ContentView(R.layout.activity_class_x)
public class ClassXFragment extends Fragment {

    String TAG = "CLASS";
    @ViewInject(R.id.show_timer_left)
    TextView countDownLeft;
    @ViewInject(R.id.video_view1)
    VideoView videoView1;
//    @ViewInject(R.id.progressBar1)
//    ProgressBar progressBar1;
    @ViewInject(R.id.list_class)
    RecyclerView list_class;
    @ViewInject(R.id.line)
    LinearLayout line;
//    @ViewInject(R.id.mask)
//    RelativeLayout mask;
    @ViewInject(R.id.className)
    TextView className;
    @ViewInject(R.id.videobox)
    FrameLayout videobox;


    MainActivity mainActivity;
    CountDownTimer countDownTimer;
    CountDownTimer ReadycountDownTimer;
    MediaPlayer mediaPlayer = null;
    boolean isReady = false;
    String video;
    ClassXAdapter adpter;
    int COLUMN = 4;
    int[] resources;
    Course mCourse;
    Interface.ClassListener classLs= new Interface.ClassListener() {
        @Override
        public void run(List<FitnessData> data) {
            updateData(data);
        }

        @Override
        public void over() {
            isPlaying = false;
            Log.i("over","");
            if(countDownTimer!=null)countDownTimer.cancel();
            if(mediaPlayer!=null){
                if (mediaPlayer != null) {//在播放状态才可以停止播放
                    mediaPlayer.release();
                    setProgress(0);
                }
            }
        }

    };
    long ReadyTime = 10;
    boolean isprepera = true;
    int videoIndex = 0;
    private String pathFile = Environment
            .getExternalStorageDirectory().getPath();
    String audio= pathFile+"/resources/sound.mp3";

    boolean isFirst = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = (MainActivity)getActivity();
        mainActivity.SetClassListener(classLs);
    }
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }
    NextLisenter nextLisenter;
    public void SetNextLisenter(NextLisenter lisenter){
        this.nextLisenter = lisenter;
    }

    public interface NextLisenter{
        void GoNext();
        void ClassOver();
    }

    @Override
    public void onViewCreated(View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        Log.i(TAG,"onViewCreated");
        initView();
        init();
        isReady = isFirst=true;
        isPlaying = false;
    }

    public void setClassData(Course coursse){
        mCourse = coursse;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    void initView(){
        className.setTypeface(typeFaceClass);
        countDownLeft.setTypeface(typeFaceNum_Ob);

        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), COLUMN);
        list_class.setLayoutManager(layoutManager);
        list_class.addItemDecoration(new GridSpacingItemDecoration(COLUMN,2, true));
        list_class.setHasFixedSize(true);
        resources = new int[]{R.drawable.recent_course1,R.drawable.recent_course2,R.drawable.recent_course3,R.drawable.recent_course4};
        List<SportUser> users = new ArrayList<>();
        adpter = new ClassXAdapter(getActivity(),users);
        list_class.setAdapter(adpter);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        Log.d(TAG,"onConfigurationChanged");
        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            double mwidth = layoutParams.height*0.5625;
            layoutParams.width = layoutParams.width>mwidth?(int)mwidth:layoutParams.width;
            videoView1.setLayoutParams(layoutParams);
        }
        super.onConfigurationChanged(newConfig);
    }

    void updateData(List<FitnessData> data){
        if(!isReady||!isAdded())return;
        List<SportUser> users = new ArrayList<>();
        if(data!=null){
            int len = data.size()>=4?4:data.size();
            for(int i =0;i<len;i++){
                SportUser user = new SportUser();
                FitnessData fd = data.get(i);
                user.setHeaderStr(fd.getUser().getAvatar());
                user.setHeartRate(fd.getHeartRate());
                user.setStrength(fd.getPercent());
                user.setCalorie(fd.getCalories());
                user.setName(fd.getUser().getName());
                user.setResource(resources[Helper.percent2State(fd.getPercent())]);
                users.add(user);
            }
        }
        adpter = new ClassXAdapter(getActivity(),users);
        list_class.setAdapter(adpter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i("onHiddenChanged","Hidden:"+hidden);
        if (hidden) {// 不在最前端界面显示
            countDownTimer.cancel();
            mediaPlayer.stop();
        } else {// 重新显示到最前端中

        }
    }
    int oldLen = -1;
    void setView(int len){
        if(oldLen!=len){
            Log.i(TAG, "setView: setview"+len);
            int screenWidth = ScreenUtils.getScreenWidth();
            int screenHeight = (int)(ScreenUtils.getScreenHeight());
            LinearLayout.LayoutParams linearLayoutParams = (LinearLayout.LayoutParams) line.getLayoutParams();
            int marginleft =(screenWidth-60)*(4-len)/8+(4-len);
            line.setTranslationX(marginleft);
            line.setLayoutParams(linearLayoutParams);
            oldLen = len;
        }
//        isFirst  =false;
    }
    @Override
    public void onDestroyView(){
        super.onDestroyView();
        isPlaying = false;
        Log.i("onDestroyView","");
        if(countDownTimer!=null)countDownTimer.cancel();
        if(mediaPlayer!=null){
            if (mediaPlayer != null) {//在播放状态才可以停止播放
                mediaPlayer.release();
            }
        }
        setProgress(0);
    }

    boolean isPlaying = false;
    void init(){
        if(countDownTimer!=null)countDownTimer.cancel();
        if(mediaPlayer!=null){
            if (mediaPlayer != null) {//在播放状态才可以停止播放
                mediaPlayer.release();
            }
        }
//        mask.setVisibility(View.VISIBLE);
        className.setText("准备");
        final List<Course.VideoUnit> videoUnits = mCourse==null?null:mCourse.getPlayList();
        videoIndex = 0;
        if(videoUnits!=null)video = videoUnits.get(videoIndex).getVideo();
        video = "android.resource://" + mainActivity.getPackageName() + "/" + R.raw.shapemp4;
        checkPath(video);
        videoView1.setOnPreparedListener(new MyPrepatedListener());
        videoView1.setOnCompletionListener(new MyCompetionListener(videoView1));
        videoView1.setVideoURI(Uri.parse(video));
        ReadycountDownTimer = new CountDownTimer(MainActivity.READY_TIME*1000, 1000) {
            public void onTick(long millisUntilFinished) {
                int inttime = (int) millisUntilFinished / 1000;
                setProgress(inttime);
                if(inttime==1){
                    new Handler().postDelayed(new Runnable(){
                        public void run() {
                            setProgress(0);
                        }
                    }, 1000);
                }
            }

            public void onFinish() {
//                mask.setVisibility(View.INVISIBLE);
                InitAudio();

                startVideo();
            }
        };
        ReadycountDownTimer.start();
    }

    boolean checkPath(String path){
        if(path==null)return false;
        int index = path.lastIndexOf('/');
        String pathTmp = path.substring(0,index);
        File file=new File(pathTmp);
        if(!file.exists())
            file.mkdir();
        try{
            if(new File(path).exists())return true;
        }catch (Exception e){
            return false;
        }
        return false;
    }

    void setProgress(int inttime ){
        countDownLeft.setText(String.valueOf(inttime)+"\"");
    }

    String oldVideo="";
    String oldAudio="";

    void startVideo(){
        try{
            if(isPlaying)return;
            Course.VideoUnit vu = mCourse.getPlayList().get(videoIndex++);
            setProgress((int)vu.getVideDuration());
            Log.i("startVideo","videoIndex:"+videoIndex);
            long playTime = vu.getVideDuration()*1000;
            video = vu.getVideo();
            Log.i("startVideo","video："+video+",playTime:"+playTime);
            if(isExist(video)){
                className.setText(vu.getName());
                if(oldVideo!=video){
                    videoView1.setVideoPath(video);// setVideoURI(Uri.parse(video));
                    oldVideo = video;
                }
            }else{
                Toast.makeText(mainActivity,"视频文件不存在",Toast.LENGTH_SHORT);
            }
            startMedia(vu.getAudio());
            countDownTimer =  new CountDownTimer(playTime, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int inttime = (int) millisUntilFinished / 1000;
                    setProgress(inttime);
                    if(inttime==1){
                        new Handler().postDelayed(new Runnable(){
                            public void run() {
                                setProgress(0);
                            }
                        }, 1000);
                    }
                }

                @Override
                public void onFinish() {
                    setProgress(0);
                    changeVideo();
                }
            };
            countDownTimer.start();
        }catch (Exception e){
            e.printStackTrace();
        }
        isPlaying = true;
    }

    boolean isExist(String path){
        try{
            File file = new File(path);
            return file.exists();
        }catch (Exception e){
            return false;
        }
    }

    void startMedia(String audio){
        if(checkPath(audio)){
            try {
                if(!oldAudio.equals(audio)){
                    if (oldAudio.length()>0)mediaPlayer.reset();
                    mediaPlayer.setDataSource(audio);
                    mediaPlayer.prepareAsync();
                    oldAudio = audio;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
//        mediaPlayer.start();
//        mediaPlayer.setLooping(true);
    }

    void changeVideo(){
        Log.i("changeVideo","下个视频");
        if(videoIndex>=mCourse.getPlayList().size()){
            new Handler().postDelayed(new Runnable(){
                public void run() {
                    endClass();
                }
            }, 1000);
        }
        else{
            final Course.VideoUnit vu = mCourse.getPlayList().get(videoIndex++);
            video = vu.getVideo();
            long playTime = vu.getVideDuration()*1000;
            Log.i("changeVideo","播放时间"+playTime);
            className.setText(vu.getName());
            setProgress((int)vu.getVideDuration());
            countDownTimer =  new CountDownTimer(playTime, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    int inttime = (int) millisUntilFinished / 1000;
                    setProgress(inttime);
                    if(inttime==1){
                        new Handler().postDelayed(new Runnable(){
                            public void run() {
                                setProgress(0);
                            }
                        }, 1000);
                    }
                }

                @Override
                public void onFinish() {
                    if(vu.getGoNext()){
                        nextLisenter.GoNext();
                        isFirst = true;
                    }
                    changeVideo();
                }
            };
            if(isExist(video)){
                if(!oldVideo.equals(video)){
                    videoView1.setVideoPath(video);// setVideoURI(Uri.parse(video));
                    oldVideo = video;
                }
            }else{
                Log.e(TAG,"视频不存在:"+video);
            }

            startMedia(vu.getAudio());
            countDownTimer.start();
        }
    }
    void endClass(){
        nextLisenter.ClassOver();
//        mainActivity.switchContent(MainActivity.classFragment,MainActivity.overFragment);
    }


    void InitAudio() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setLooping(true);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                InitAudio();
                return false;
            }
        });
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                Log.i(TAG,"音频准备就绪 开始播放");
                mediaPlayer.setVolume(1f, 1f);
                mediaPlayer.start();
            }
        });
            try {
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            } catch (Exception e) {
                e.printStackTrace();
            }
//        }
    }

    public class MyPrepatedListener implements MediaPlayer.OnPreparedListener {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            videoView1.start();
        }
    }

    public class MyCompetionListener implements MediaPlayer.OnCompletionListener {
        final VideoView videoView;
        MyCompetionListener(VideoView videoView) {
            this.videoView = videoView;
        }

        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            videoView.start();
        }
    }
}
